<?php

namespace app\yy\services;

use app\yy\model\Order as OrderModel;
use app\yy\model\OrderGoods as GoodsModel;
use app\yy\model\Currency as CurrencyModel;

class Order extends BaseService
{
    public function getOrderList($list)
    {
        foreach ($list as $info) {
            try{
                // 获取网站最后一笔订单交易时间
                $lastDate = OrderModel::where('domain_id', $info['id'])->order('date_modified DESC')->value('date_modified');
                if (empty($lastDate)) {
                    $lastDate = date("Y-m-d H:i:s", strtotime("-100 day"));
                }
                $url = 'https://' . $info['domain'] . $info['order_api'] . '&lastDate=' . $lastDate;
                $option = array('ssl' => array('verify_peer' => false, 'verify_peer_name' => false));
                $content = @file_get_contents($url, false, stream_context_create($option));
                if($content){
                    $orders = json_decode($content, true);
                    if ($orders) {
                        // 订单保存
                        foreach ($orders as $order) {

                            $this->saveOrder($order, $info['id']);
                        }
                    }
                }
                // echo $info['domain'] . '网站接口访问成功'.'<br>';
            } catch (\ErrorException $e) {
                echo $info['domain'] . '网站接口访问失败'.'<br>';
                die;
            }
        }
    }

    /**
     * 保存订单数据
     * @return void
     */
    public function saveOrder($order, $domain_id)
    {
        $order['domain_id'] = $domain_id;
        $orderProducts = $order['product'];
        unset($order['product']);

        $order['usd_amount'] = $this->currencyRate($order['currency'], $order['amount']);
        // 查询订单是否存在
        if (($order_id = OrderModel::where('order_number', $order['order_number'])->value('id'))) {
            OrderModel::where('id', $order_id)->update($order);
            $orderInfo['id'] = $order_id;
            GoodsModel::where('order_id', $order_id)->delete();
        } else {
            $orderInfo = OrderModel::create($order);
        }

        $goods = [];
        foreach ($orderProducts as $product) {
            $product['order_id'] = $orderInfo['id'];
            $product['date_modified'] = $order['date_modified'];
            $product['domain_id'] = $domain_id;
            $product['status'] = $order['status'];
            $goods[] = $product;
        }
        GoodsModel::insertAll($goods);


    }

    /**
     * 货币转换
     * @param $currency
     * @param $amount
     * @return
     */
    public function currencyRate($currency, $amount)
    {
        $rate = CurrencyModel::where('code', $currency)->value('rate');
        return round(($amount * $rate), 2);
    }
}